package com.zhx.threadcoreknowledge.threadobjectclasscommonmethod;

/**
 * @author ：zhanghaixuan
 * @date ：Created in 2019-10-03 11:37
 * 用途         ： 三个线程  线程1和线程2被阻塞   线程3去唤醒线程
 * 分别使用 notify和notifyall 调用
 * start 先执行不代表线程先启动
 */
public class WaitNotifyAll implements Runnable {

    private static Object resourceA = new Object();

    @Override
    public void run() {
        synchronized (resourceA) {
            System.out.println(Thread.currentThread().getName() + "开始执行了:" + Thread.currentThread().getState());
            try {
                System.out.println(Thread.currentThread().getName() + "等待下一步的开始");
                resourceA.wait();
                System.out.println(Thread.currentThread().getName() + "获取到了锁");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        WaitNotifyAll waitNotifyAll = new WaitNotifyAll();

        Thread thread1 = new Thread(waitNotifyAll);
        Thread thread2 = new Thread(waitNotifyAll);

        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (resourceA) {
                    System.out.println(Thread.currentThread().getName() + "开始运行");
                    resourceA.notifyAll();
                    System.out.println(Thread.currentThread().getName() + "成功 notifyAll");
                }
            }
        });

        thread1.start();
        thread2.start();

        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        thread3.start();
    }
}
